"""
认证相关API
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from app.extensions import db
from app.models import User

auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')


@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return jsonify({'message': '用户名和密码不能为空'}), 400
        
        user = User.query.filter_by(username=username).first()
        
        if not user or not user.check_password(password):
            return jsonify({'message': '用户名或密码错误'}), 401
        
        if not user.is_active:
            return jsonify({'message': '账户已被禁用'}), 401
        
        # 创建访问令牌
        access_token = create_access_token(identity=str(user.id))
        
        return jsonify({
            'access_token': access_token,
            'user': user.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'message': f'登录失败: {str(e)}'}), 500


@auth_bp.route('/me', methods=['GET'])
@jwt_required()
def get_current_user():
    """获取当前用户信息"""
    try:
        user_id = int(get_jwt_identity())
        user = User.query.get(user_id)
        
        if not user:
            return jsonify({'message': '用户不存在'}), 404
        
        # 获取用户菜单
        menus = []
        if user.role and user.role.menus:
            # 获取一级菜单
            parent_menus = [menu for menu in user.role.menus if menu.parent_id is None and menu.is_active]
            parent_menus.sort(key=lambda x: x.sort_order)
            
            for menu in parent_menus:
                menu_dict = menu.to_dict()
                menus.append(menu_dict)
        
        return jsonify({
            'user': user.to_dict(),
            'menus': menus
        }), 200
        
    except Exception as e:
        return jsonify({'message': f'获取用户信息失败: {str(e)}'}), 500


@auth_bp.route('/logout', methods=['POST'])
@jwt_required()
def logout():
    """用户退出登录"""
    # JWT无状态，前端删除token即可
    return jsonify({'message': '退出登录成功'}), 200